#ParallelPlatform Project - A web platform to distribute and share knowledge
#Copyright (C) 2011  Daniel Guerrero Martinez & Sergio Rodriguez Lumley
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from uuid import uuid1
from django.conf import settings
from PIL import Image
from ParallelPlatform.wiki.models import PageRevision
import os


def scale(fname, maxWidth, maxHeight, fname_scaled):
    try:
        img = Image.open(fname)
    except:
        print 'Unable to open ' + fname
    
    # We check if size is suitable for saving
    width  = img.size[0]
    height = img.size[1]
    scalingFactor = 1.0

    # max/min cannot have more difference than 16:9
    if (float(max(width, height))/float(min(width,height)) < 16.0/9.0):
        if max(width, height) > 800:
            scalingFactor = 800.0/max(width, height)
        width  = int(width  * scalingFactor)
        height = int(height * scalingFactor)
    else: # If proportions are not as desired, we just deform image
        if width > 800:
            width = 800
        if height > 800:
            height = 800
    
    img = img.resize((width, height), Image.ANTIALIAS)
    
    try:
        img.save(fname_scaled)
    except:
        print 'Unable to save in ' + fname_scaled
    
class Resource(models.Model):
    
    id = models.AutoField(primary_key=True)
    onCreate = models.DateTimeField(auto_now = False,auto_now_add=True)
    type = models.CharField( max_length=5 )
    file = models.FileField( null=False, upload_to="resources" )
    
    pageRevision = models.ManyToManyField(PageRevision, related_name = 'resources')
    
    
    def save(self):
        super(Resource,self).save()
        
        type = self.file.name[ self.file.name.rfind(".")+1:len(self.file.name)].lower();
        for t in settings.RESOURCES_TYPES:
            if type in settings.RESOURCES_TYPES[t]:
                subDir = t
        newName = os.path.join(os.path.dirname(self.file.path), subDir)
        
        if not os.path.exists(newName):
            os.mkdir(newName)
            
        newName = os.path.join(newName, str(self.id) +'.'+type )
        
        if type in settings.RESOURCES_TYPES['img']:
            scale(self.file.path,800,800,newName)
            os.remove(self.file.path)
        else:
            os.rename(self.file.path, newName)
            
                
        self.file.name = os.path.join( os.path.dirname(self.file.name), subDir , os.path.basename(newName))
        
        super(Resource,self).save()
        
#        class Meta:
#            permissions = (
#                           ("add_resources","Can edit page, edit include disable page"),
#                           )

import re

def createLink(sender, **kwargs):
    rev = kwargs['instance']
    find = re.findall("media/(?P<dir>resources/[\w./]+)", rev.content)
    for src in find:
        print src
        try:
            src = Resource.objects.get(file=os.path.normpath(src))
            if rev not in src.pageRevision.all():
                src.pageRevision.add(rev)
        except:
            pass
    
    
def deleteResourcesOfRevision(sender, **kwargs):
    rev = kwargs['instance']
    for src in rev.resources.all():
        if src.pageRevision.count() <= 1:
            src.delete()
    
    garbageCollector()

from datetime import datetime,timedelta

def garbageCollector():
    time = datetime.now()-timedelta(2)
    for src in Resource.objects.filter(onCreate__lt=time):
        if src.pageRevision.count() == 0:
            src.delete()

        
from django.db.models.signals import post_save, pre_delete

post_save.connect(createLink, sender=PageRevision)
pre_delete.connect(deleteResourcesOfRevision, sender=PageRevision)


    
